package dao;
import tool.OtherToolClass;
import tool.RowMapper;
import tool.BaseDao;
import java.util.List;
import java.sql.SQLException;
import java.sql.ResultSet;
import entity.TypetbEntity;
import dao.mapper.TypetbDAOI;

/**
 *@author JiangFan
 */
public class TypetbDAO extends BaseDao implements TypetbDAOI {

	OtherToolClass ot =new OtherToolClass ();

	/**
	 * @param type_name
	 *         根据传入类型名称查询类型列表是否存在该类型
	 * @return
	 */
	@Override
	public TypetbEntity selectTypeOne (String type_name) throws SQLException, ClassNotFoundException {
		String sql="select *from typetb where type_name=?";
		Object[] param={type_name};
		//调用查询单个方法
		return this.excuteQueryOne (sql, param,new TypetbRowMapper () );
	}

	/**
	 * @return
	 */
	@Override
	public List <TypetbEntity> selectTypeAll ()
			throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
		String sql="select *from typetb";
		//调用查询方法
		return this.executeQuery (sql,null,new TypetbRowMapper ());
	}

	/**
	 * @param te
	 *         在类型列表添加新类型
	 * @return
	 */
	@Override
	public int insertType (TypetbEntity te) throws SQLException, ClassNotFoundException {
		String sql="insert into typetb values(?,?,?)";
		//调用添加方法
		Object[] param={getID (),te.getType_name (),te.getType_father ()};
		return this.update (sql,param);
	}

	/**
	 * @param fatype_name
	 *         根据父类类型查询父类编号
	 * @return
	 */
	@Override
	public TypetbEntity selectFaTypeOneByName (String fatype_name) throws SQLException, ClassNotFoundException {
		//输入类型名称，查询类型是否存在，
		String sql="select type_id from typetb where type_name=?";
		Object[] param={fatype_name};
		return this.excuteQueryOne (sql,param,new TypetbRowMapper ());
	}

	/** 查询所有父类名
	 * @return
	 */
	@Override
	public List<TypetbEntity> selectFaTyAll () throws SQLException, ClassNotFoundException {
		String sql="select type_name from typetb";
		return this.executeQuery (sql,null,new TypetbRowMapper ());
	}

	private String getID() throws SQLException, ClassNotFoundException {
		String sql="select type_id from typetb";
		return ot.getIDtwo (sql,"typ",new TypetbRowMapper ());
	}
}
class TypetbRowMapper implements RowMapper<TypetbEntity>{
	@Override
	public TypetbEntity rowmap(ResultSet set) throws  SQLException{
		return new TypetbEntity(
				set.getString("type_id"),
				set.getString("type_name"),
				set.getString ("type_father")
		);
	}
}
